<?php
declare(strict_types=1);

namespace SixShop\MakerBundle\Generator;

use Symfony\Component\Console\Style\SymfonyStyle;

class EntityGenerator
{
    private string $templatesPath;

    public function __construct()
    {
        $this->templatesPath = __DIR__ . '/../../templates';
    }

    /**
     * Generate entity file
     */
    public function generateEntity(
        string $tableName, 
        string $tableComment, 
        array $fields, 
        array $extensionInfo, 
        string $targetPath, 
        SymfonyStyle $io
    ): bool {
        try {
            $entityName = $this->generateEntityName($tableName);
            $entityPath = $targetPath . '/src/Entity';
            
            // Ensure entity directory exists
            if (!is_dir($entityPath)) {
                if (!mkdir($entityPath, 0755, true)) {
                    $io->error("无法创建实体目录: {$entityPath}");
                    return false;
                }
            }
            
            $fileName = $entityName . '.php';
            $filePath = $entityPath . '/' . $fileName;
            
            // Check if file exists
            if (file_exists($filePath)) {
                if (!$io->confirm("实体文件已存在: {$fileName}，是否覆盖?", false)) {
                    $io->text("跳过实体文件: {$fileName}");
                    return true;
                }
            }
            
            // Prepare template variables
            $entityName = $this->generateEntityName($tableName);
            $modelName = $this->generateModelName($tableName);
            $namespace = rtrim($extensionInfo['namespace'], '\\') . '\\';
            $requiredFields = $this->getRequiredFields($fields);
            
            // Generate content using template
            ob_start();
            include $this->templatesPath . '/src/Entity/Entity.php.tpl.php';
            $content = ob_get_clean();
            
            // Write file
            if (file_put_contents($filePath, $content) !== false) {
                $io->text("✓ 生成实体文件: src/Entity/{$fileName}");
                return true;
            } else {
                $io->error("✗ 无法写入实体文件: {$fileName}");
                return false;
            }
            
        } catch (\Exception $e) {
            $io->error('生成实体文件时发生错误: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Generate entity class name from table name
     */
    private function generateEntityName(string $tableName): string
    {
        // Remove common prefixes
        $tableName = preg_replace('/^(tbl_|tb_|t_)/', '', $tableName);
        
        // Convert to PascalCase
        $parts = explode('_', $tableName);
        $parts = array_map('ucfirst', $parts);
        
        return implode('', $parts) . 'Entity';
    }
    
    /**
     * Generate model class name from table name
     */
    private function generateModelName(string $tableName): string
    {
        // Remove common prefixes
        $tableName = preg_replace('/^(tbl_|tb_|t_)/', '', $tableName);
        
        // Convert to PascalCase
        $parts = explode('_', $tableName);
        $parts = array_map('ucfirst', $parts);
        
        return implode('', $parts) . 'Model';
    }
    
    /**
     * Get required fields for validation
     */
    private function getRequiredFields(array $fields): array
    {
        $required = [];
        $excludeFields = ['id', 'create_time', 'update_time', 'delete_time'];
        
        foreach ($fields as $field) {
            if (!in_array($field['name'], $excludeFields) && 
                (!isset($field['null']) || !$field['null'])) {
                $required[] = $field;
            }
        }
        
        return $required;
    }
}